import { defineComponent, ref, PropType, computed } from 'vue'
import { useWorkflowStore } from '../stores/workflow'
import type { Workflow } from '../types/workflow'

export default defineComponent({
  name: 'WorkflowList',
  props: {
    currentWorkflow: {
      type: Object as PropType<Workflow | null>,
      default: null,
    },
  },
  emits: ['edit'],
  setup(props, { emit }) {
    const store = useWorkflowStore()
    const searchQuery = ref('')
    const editingWorkflow = ref<string | null>(null)
    const editingName = ref('')
    const showIconPicker = ref(false)
    const selectedWorkflowId = ref<string | null>(null)

    const filteredWorkflows = computed(() => {
      if (!searchQuery.value) return store.workflows
      const query = searchQuery.value.toLowerCase()
      return store.workflows.filter(workflow =>
        workflow.name.toLowerCase().includes(query)
      )
    })

    const createWorkflow = () => {
      const newWorkflow = store.createWorkflow()
      emit('edit', newWorkflow)
    }

    const handleEdit = (workflow: Workflow) => {
      emit('edit', workflow)
    }

    const handleDelete = (workflow: Workflow, event: MouseEvent) => {
      event.stopPropagation()
      // 显示删除确认对话框
      showDeleteConfirm.value = true
      selectedWorkflowId.value = workflow.id
    }

    const startRename = (workflow: Workflow, event: MouseEvent) => {
      event.stopPropagation()
      editingWorkflow.value = workflow.id
      editingName.value = workflow.name
    }

    const handleRename = (workflow: Workflow) => {
      const trimmedName = editingName.value.trim()
      if (trimmedName && trimmedName.length <= MAX_NAME_LENGTH) {
        store.updateWorkflow({
          ...workflow,
          name: trimmedName,
        })
      }
      editingWorkflow.value = null
    }

    const openIconPicker = (workflow: Workflow, event: MouseEvent) => {
      event.stopPropagation()
      selectedWorkflowId.value = workflow.id
      showIconPicker.value = true
    }

    const handleIconSelect = (icon: string) => {
      if (selectedWorkflowId.value) {
        const workflow = store.workflows.find(
          w => w.id === selectedWorkflowId.value
        )
        if (workflow) {
          store.updateWorkflow({
            ...workflow,
            icon: icon.startsWith('i-mdi-') ? icon : `i-mdi-${icon}`,
          })
        }
      }
      showIconPicker.value = false
    }

    // 删���确认对话框状态
    const showDeleteConfirm = ref(false)

    const confirmDelete = () => {
      if (selectedWorkflowId.value) {
        store.deleteWorkflow(selectedWorkflowId.value)
        if (props.currentWorkflow?.id === selectedWorkflowId.value) {
          emit('edit', null)
        }
      }
      showDeleteConfirm.value = false
    }

    // 在 setup 中添加更多图标
    const iconList = [
      // 流程相关
      'i-mdi-sitemap',
      'i-mdi-source-branch',
      // 触发器相关
      'i-mdi-keyboard',
      'i-mdi-text-search',
      'i-mdi-clock-outline',
      'i-mdi-calendar',
      'i-mdi-bell-outline',
      'i-mdi-lightning-bolt',
      'i-mdi-gesture-tap',
      // 动作相关
      'i-mdi-script-text',
      'i-mdi-console',
      'i-mdi-cog-outline',
      'i-mdi-robot',
      'i-mdi-api',
      'i-mdi-function',
      'i-mdi-code-braces',
      'i-mdi-code-tags',
      // 数据相关
      'i-mdi-database',
      'i-mdi-file-outline',
      'i-mdi-folder-outline',
      'i-mdi-xml',
      'i-mdi-table',
      'i-mdi-chart-box-outline',
      // 通信相关
      'i-mdi-email-outline',
      'i-mdi-message-outline',
      'i-mdi-web',
      'i-mdi-webhook',
      'i-mdi-wifi',
      'i-mdi-broadcast',
      'i-mdi-cloud-outline',
      // 系统相关
      'i-mdi-desktop-mac',
      'i-mdi-laptop',
      'i-mdi-cellphone',
      'i-mdi-tablet',
      'i-mdi-monitor',
      'i-mdi-keyboard-settings-outline',
      // 工具相关
      'i-mdi-tools',
      'i-mdi-hammer-wrench',
      'i-mdi-puzzle-outline',
      'i-mdi-package',
      'i-mdi-application',
      'i-mdi-apps',
      'i-mdi-view-grid-outline',
    ]

    const MAX_NAME_LENGTH = 20

    // 在 setup 中添加
    const customIconInput = ref('')
    const iconInputError = ref(false)

    // 处理自定义图标输入
    const handleCustomIconSubmit = () => {
      const iconName = customIconInput.value.trim()
      if (!iconName) return

      // 如果用户输入的已经包含 i-mdi- 前缀，直接使用
      const fullIconName = iconName.startsWith('i-mdi-')
        ? iconName
        : `i-mdi-${iconName}`

      // 验证图标是否存在
      const testElement = document.createElement('i')
      testElement.className = fullIconName
      document.body.appendChild(testElement)
      const computedStyle = window.getComputedStyle(testElement)
      const isValidIcon = computedStyle.content !== ''
      document.body.removeChild(testElement)

      if (isValidIcon) {
        handleIconSelect(fullIconName)
        iconInputError.value = false
        customIconInput.value = ''
      } else {
        iconInputError.value = true
      }
    }

    return () => (
      <div class="h-full flex flex-col bg-[#2D1A45]">
        {/* 顶部搜索和新建 */}
        <div class="p-4 space-y-4">
          <div class="relative">
            <input
              type="text"
              v-model={searchQuery.value}
              placeholder="搜索工作流..."
              class="w-full pl-9 pr-4 py-2 bg-[#3D2A55] border border-[#4D3A65] rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-[#663399] focus:ring-1 focus:ring-[#663399]"
            />
            <i class="i-mdi-magnify text-gray-400 absolute left-3 top-2.5 text-lg" />
          </div>
          <button
            onClick={createWorkflow}
            class="w-full px-4 py-2 bg-[#663399] text-white rounded-lg hover:bg-[#7B41B7] transition-colors flex items-center justify-center space-x-2"
          >
            <i class="i-mdi-plus text-lg" />
            <span>新建工作流</span>
          </button>
        </div>

        {/* 工作流列表 */}
        <div class="flex-1 overflow-y-auto px-2">
          {filteredWorkflows.value.map(workflow => (
            <div
              key={workflow.id}
              class={`
                group p-3 mb-2 rounded-lg cursor-pointer
                transition-colors duration-200
                ${
                  props.currentWorkflow?.id === workflow.id
                    ? 'bg-[#4D3A65]'
                    : 'hover:bg-[#3D2A55]'
                }
              `}
              onClick={() => handleEdit(workflow)}
            >
              <div class="flex items-center justify-between w-full">
                <div class="flex items-center space-x-3 min-w-0 flex-1">
                  <div
                    class="w-8 h-8 bg-[#663399] rounded-lg flex-shrink-0 flex items-center justify-center opacity-80 cursor-pointer hover:opacity-100"
                    onClick={e => openIconPicker(workflow, e)}
                  >
                    <i
                      class={`${workflow.icon || 'i-mdi-flow-parallel'} text-white text-xl`}
                    />
                  </div>
                  <div class="min-w-0 flex-1">
                    {editingWorkflow.value === workflow.id ? (
                      <input
                        type="text"
                        v-model={editingName.value}
                        maxLength={MAX_NAME_LENGTH}
                        class="bg-[#2D1A45] text-white px-2 py-1 rounded border border-[#663399] text-sm w-full"
                        onBlur={() => handleRename(workflow)}
                        onKeyup={(e: KeyboardEvent) => {
                          if (e.key === 'Enter') handleRename(workflow)
                          if (e.key === 'Escape') editingWorkflow.value = null
                        }}
                        onClick={e => e.stopPropagation()}
                        autoFocus
                      />
                    ) : (
                      <div
                        class="text-white text-sm font-medium truncate max-w-[140px]"
                        title={workflow.name}
                      >
                        {workflow.name}
                      </div>
                    )}
                    <div class="text-gray-400 text-xs">
                      {workflow.nodes.length} 个节点
                    </div>
                  </div>
                </div>
                <div class="flex space-x-2 flex-shrink-0 ml-2">
                  <button
                    onClick={e => startRename(workflow, e)}
                    class="text-gray-400 hover:text-white transition-colors opacity-0 group-hover:opacity-100"
                  >
                    <i class="i-mdi-pencil text-lg" />
                  </button>
                  <button
                    onClick={e => handleDelete(workflow, e)}
                    class="text-gray-400 hover:text-red-500 transition-colors opacity-0 group-hover:opacity-100"
                  >
                    <i class="i-mdi-delete text-lg" />
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* 底部信息 */}
        <div class="p-4 border-t border-[#3D2A55]">
          <div class="text-xs text-gray-400 flex items-center justify-between">
            <span>共 {store.workflows.length} 个工作流</span>
            <span>按 ⌘K 搜索</span>
          </div>
        </div>

        {/* 删除确认对话框 */}
        {showDeleteConfirm.value && (
          <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-[#2D1A45] rounded-lg p-6 max-w-sm w-full mx-4 border border-[#3D2A55]">
              <h3 class="text-lg font-medium text-white mb-2">确认删除</h3>
              <p class="text-gray-300 mb-6">
                删除后无法恢复，是否确认删除该工作流？
              </p>
              <div class="flex justify-end space-x-3">
                <button
                  onClick={() => (showDeleteConfirm.value = false)}
                  class="px-4 py-2 text-gray-300 hover:text-white transition-colors"
                >
                  取消
                </button>
                <button
                  onClick={confirmDelete}
                  class="px-4 py-2 bg-red-500 text-white rounded-lg hover:bg-red-600 transition-colors"
                >
                  删除
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 图标选择器 */}
        {showIconPicker.value && (
          <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
            <div class="bg-[#2D1A45] rounded-lg p-6 max-w-2xl w-full mx-4 border border-[#3D2A55]">
              <div class="flex justify-between items-center mb-4">
                <h3 class="text-lg font-medium text-white">选择图标</h3>
                <button
                  onClick={() => {
                    showIconPicker.value = false
                    customIconInput.value = ''
                    iconInputError.value = false
                  }}
                  class="text-gray-400 hover:text-white transition-colors"
                >
                  <i class="i-mdi-close text-xl" />
                </button>
              </div>

              {/* 自定义图标输入 */}
              <div class="mb-4">
                <div class="flex space-x-2">
                  <input
                    type="text"
                    v-model={customIconInput.value}
                    placeholder="输入图标名称，如: account 或 i-mdi-account"
                    class={`
                      flex-1 px-3 py-2 
                      bg-[#3D2A55] 
                      border 
                      rounded-lg 
                      text-white 
                      placeholder-gray-400 
                      focus:outline-none 
                      focus:ring-1 
                      ${
                        iconInputError.value
                          ? 'border-red-500 focus:border-red-500 focus:ring-red-500'
                          : 'border-[#4D3A65] focus:border-[#663399] focus:ring-[#663399]'
                      }
                    `}
                    onKeyup={(e: KeyboardEvent) => {
                      if (e.key === 'Enter') {
                        handleCustomIconSubmit()
                      }
                    }}
                  />
                  <button
                    onClick={handleCustomIconSubmit}
                    class="px-4 py-2 bg-[#663399] text-white rounded-lg hover:bg-[#7B41B7] transition-colors"
                  >
                    应用
                  </button>
                </div>
                {iconInputError.value && (
                  <p class="mt-1 text-sm text-red-500">
                    图标不存在，请输入有效的 MDI 图标名称
                  </p>
                )}
              </div>

              {/* 预设图标列表 */}
              <div class="grid grid-cols-8 gap-3 max-h-[400px] overflow-y-auto p-2">
                {iconList.map(icon => (
                  <div
                    key={icon}
                    class="w-12 h-12 rounded-lg bg-[#3D2A55] flex items-center justify-center cursor-pointer hover:bg-[#4D3A65] transition-colors group relative"
                    onClick={() => handleIconSelect(icon)}
                  >
                    <i class={`${icon} text-2xl text-white`} />
                    <div class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-2 py-1 bg-[#1A1A1A] text-white text-xs rounded opacity-0 group-hover:opacity-100 whitespace-nowrap pointer-events-none transition-opacity">
                      {icon.replace('i-mdi-', '')}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    )
  },
})
